﻿using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using Autofac.Integration.Web;

namespace Wechat.ASP
{
    public class AutoFacBootStrapper : IContainerProviderAccessor
    {
        static IContainerProvider _containerProvider;

        // Instance property that will be used by Autofac HttpModules
        // to resolve and inject dependencies.
        public IContainerProvider ContainerProvider => _containerProvider;

        public static void CoreAutoFacInit()
        {
            var builder = new ContainerBuilder();
          
            SetupResolveRules(builder);

            _containerProvider = new ContainerProvider(builder.Build());
        }

        private static void SetupResolveRules(ContainerBuilder builder)
        {

            //加载数据仓储层
            var assemblyDao = Assembly.Load("Wechat.Dao");

            //业务管理层
            var assemblyManager = Assembly.Load("Wechat.Manager");

            builder.RegisterAssemblyTypes(assemblyDao).Where(
                type =>
                    type.Name.EndsWith("Repository") && //以Repository结尾的仓储类
                    type.Namespace.Equals("Wechat.Dao.Implement") //限定仓储实例命名空间
                    ).AsImplementedInterfaces().PropertiesAutowired().SingleInstance(); //实例化全部匹配仓储类

            builder.RegisterAssemblyTypes(assemblyManager).Where(
                type =>
                    type.Name.EndsWith("Manager") && //以Manager结尾的业务类
                    type.Namespace.Equals("Wechat.Manager.Implement")) //限定业务实例命名空间
                .AsImplementedInterfaces().PropertiesAutowired().SingleInstance(); //实例化全部匹配业务类

            //builder.RegisterType<待注入的类类型>().AsSelf().PropertiesAutowired();
        }
    }
}